#include "server.h"
#include <QMessageBox>
#include "clientsocket.h"
Server::Server(quint16 port, QObject * parent):QTcpServer (parent)
{
    this->port = port;

}
//开始监听
bool Server::startListen(){
    //监听本机ip和端口
    bool b = listen(QHostAddress::Any, this->port);
    if(b){
        //启动监听成功
        QMessageBox::about(nullptr, "提示", "启动成功");
    }else{
        QMessageBox::warning(nullptr, "警告", "启动失败");
    }
    return b;


}
//新连接到达
void Server::incomingConnection(qintptr handle){

    //创建clientSocket
    ClientSocket * clientSocket = new ClientSocket(handle, this);
    QString s = clientSocket->peerAddress().toString()+":";
    s.append(QString::number(clientSocket->peerPort(), 10));
    emit(signalNewConnection(s)); //发消息

    clientSocketList.push_back(clientSocket);//添加到集合中
    currentClientSocket = clientSocket;
    //事件绑定
    connect(clientSocket, SIGNAL(clientDisconnected(ClientSocket *)), this, SLOT(slotClientDisconnected(ClientSocket *)));
    connect(clientSocket, SIGNAL(receiveData(ClientSocket * , QString)), this, SLOT(slotReceiveData(ClientSocket *, QString)));
}
//接收客户端连接断开的通知
void Server::slotClientDisconnected(ClientSocket * clientSocket){
    clientSocket->close();
    
    clientSocketList.removeOne(clientSocket);

    //可以发信号
    QString s = clientSocket->peerAddress().toString()+":";
    s.append(QString::number(clientSocket->peerPort(), 10));
    emit(signalDisconnection(s));
    delete clientSocket;
    if(clientSocketList.length() >0){
        currentClientSocket = clientSocketList.last();
    }else{
        currentClientSocket = nullptr;
    }
}
//接收数据
void Server::slotReceiveData(ClientSocket * clientSocket, QString data){
    currentClientSocket = clientSocket;
    QString clientMsg = clientSocket->peerAddress().toString()+":";
    quint16 port = clientSocket->peerPort();

    clientMsg.append(QString::number(port, 10));

    emit(signalReceiveData(clientMsg, data));//发消息

}
